<template>
    <div class="main-content">
        <el-card class="left-tree">
            <div slot="header" class="clearfix">
                <span>组织架构</span>
                <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
            </div>
            <el-tree
                :data="deptDataList"
                :props="deptTreeProps"
                default-expand-all
                highlight-current
                :expand-on-click-node="false"
                @node-click="handleNodeClick"
            ></el-tree>
        </el-card>
        <div class="page-container">
            <!--工具栏-->
            <TableHead
                :config="tableHeaderConfig"
                :searchdata.sync="filters"
                v-show="showSearch"
                @parentPageList="findPageList()"
            >
                <template slot="isLocked">
                    <el-select v-model="filters.isLocked" placeholder="精确查询" size="mini" clearable>
                        <el-option label="启用" value="0"></el-option>
                        <el-option label="禁用" value="1"></el-option>
                    </el-select>
                </template>
            </TableHead>
            <el-card class="card-box">
                <table-tool-bar :showSearch.sync="showSearch" @queryTable="findPageList" :columns="columns">
                    <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增</el-button>
                </table-tool-bar>
                <Table
                    v-model="filters.pageNum"
                    :columns="columns"
                    :data="tableList"
                    :total="total"
                    :loading="loading"
                    showNo
                    @getPageList="findPageList"
                >
                    <template slot="userName" slot-scope="{ scope }">
                        <i class="el-icon-user-solid" style="color: #409eff" v-if="scope.row.isAdmin === 1"></i>
                        {{ scope.row.userName }}
                    </template>
                    <template slot="structure" slot-scope="{ scope }">
                        {{ scope.row.companyName }}
                        <br />
                        {{ scope.row.deptName }}
                    </template>
                    <template slot="status" slot-scope="{ scope }">
                        <el-switch
                            v-model="scope.row.isLocked"
                            :active-value="0"
                            :inactive-value="1"
                            @change="handleEnable(scope.row)"
                        ></el-switch>
                    </template>
                    <template slot="oper" slot-scope="{ scope }">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit('edit', scope.row)"
                            v-if="scope.row.isLocked !== 1"
                        >
                            编辑
                        </el-button>
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-user"
                            @click="handleRole(scope.row)"
                            v-if="scope.row.isLocked !== 1"
                        >
                            角色
                        </el-button>
                    </template>
                </Table>
            </el-card>

            <EditItem
                v-model="dialogVisible"
                :data-form="dataForm"
                :dialog-config="dialogConfig"
                :data-form-rules="dataFormRules"
                :dialog-tag="dialogTag"
                width="600px"
                ref="formDialog"
                @submitForm="submitForm"
            >
                <template slot="deptId">
                    <tree-select
                        v-model="dataForm.deptPath"
                        placeholder="请选择"
                        :disabled="dialogTag === 'add'"
                        :defaultExpandAll="true"
                        :treeOptions="formDeptList"
                        :treeProps="deptTreeProps"
                        @selectChange="deptSelect"
                    />
                </template>
            </EditItem>
            <auth-role
                v-model="roleDialog"
                :roleList="roleList"
                :selectList="selectRoleList"
                @submitRole="submitRole"
            ></auth-role>
        </div>
    </div>
</template>
<script>
import TreeSelect from '@/components/TreeSelect'
import TableHead from '@/components/TableHeadSearch'
import EditItem from '@/components/EditItem'
import TableToolBar from '@/components/TableToolBar'
import AuthRole from './authRole.vue'
import { confirm, deepClone } from '@/utils/utils'
import { isEmailRegExp, phoneNumRegExp } from '@/utils/validate.js'
import {
    getUserList,
    addUser,
    editUser,
    userEnable,
    getAllRoleList,
    userbindRole,
    getRoletByUser,
    getDeptTableList,
    resetPW
} from '@/api/system/user.js'
export default {
    name: 'user',
    components: {
        TableToolBar,
        TreeSelect,
        TableHead,
        EditItem,
        AuthRole
    },
    data() {
        return {
            showSearch: true,
            loading: false,
            roleDialog: false,
            roleList: [],
            tableList: [],
            total: 0,
            tableHeaderConfig: [
                { title: '用户名', code: 'userName', type: 'input' },
                { title: '姓名', code: 'name', type: 'input' },
                { title: '手机号', code: 'mobile', type: 'input' },
                { title: '邮箱', code: 'email', type: 'input' },
                { title: '是否启用', slot: 'isLocked' }
            ],
            filters: {
                pageNum: 1,
                pageSize: 10,
                companyId: '',
                deptId: '',
                isLocked: null,
                name: '',
                userName: ''
            },
            columns: [
                { slot: 'userName', label: '用户名', visible: true, key: 'userName' },
                { prop: 'name', label: '姓名', visible: true, key: 'name' },
                { slot: 'structure', label: '公司/部门', visible: true, minWidth: 110, key: 'structure' },
                { slot: 'status', label: '状态', align: 'center', width: '80', visible: true, key: 'status' },
                { prop: 'mobile', label: '手机', width: '100', visible: true, key: 'mobile' },
                { prop: 'email', label: '邮箱', visible: true, key: 'email' },
                { label: '创建人/创建时间', type: 'createUser', visible: true, key: 'createUser' },
                { label: '更新人/更新时间', type: 'updateUser', visible: true, key: 'updateUser' },
                { slot: 'oper', label: '操作', align: 'center', minWidth: 130, visible: true, key: 'oper' }
            ],
            dataFormRules: {
                userName: [
                    {
                        required: true,
                        message: '请输入用户名',
                        trigger: 'blur'
                    },
                    {
                        pattern: /^[0-9a-zA-Z]*$/g,
                        message: '只能输入字母或数字',
                        trigger: 'blur'
                    },
                    {
                        max: 10,
                        message: '长度在10个字符以内',
                        trigger: 'blur'
                    }
                ],
                name: [
                    {
                        required: true,
                        message: '请输入姓名',
                        trigger: 'blur'
                    },
                    {
                        max: 10,
                        message: '长度在10个字符以内',
                        trigger: 'blur'
                    }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {
                        type: 'email',
                        pattern: isEmailRegExp,
                        message: '请输入正确的邮箱地址',
                        trigger: 'blur'
                    }
                ],
                mobile: [
                    // { required: true, message: '请输入手机号', trigger: 'blur' },
                    {
                        pattern: phoneNumRegExp,
                        message: '请输入正确的手机号',
                        trigger: 'blur'
                    }
                ]
            },
            filterColumns: [],
            dialogVisible: false, // 新增编辑界面是否显示
            deptDataList: [],
            formDeptList: [],
            roles: [],
            // 新增编辑界面数据
            dataFormDefault: {
                id: '',
                userName: '', //用户名
                // salt: '',
                name: '', //姓名
                deptPath: '',
                email: '',
                mobile: null
            },
            dataForm: {},
            // dialog 要渲染的数据json
            dialogConfig: [
                {
                    title: '用户名',
                    code: 'userName',
                    type: 'input',
                    disabled: 'edit',
                    maxlength: 10
                },
                {
                    title: '姓名',
                    code: 'name',
                    type: 'input',
                    maxlength: 10
                },
                {
                    title: '部门',
                    code: 'deptId',
                    slot: 'deptId'
                },
                {
                    title: '邮箱',
                    code: 'email',
                    type: 'input'
                },
                {
                    title: '手机号',
                    code: 'mobile',
                    type: 'input'
                }
            ],
            dialogTag: 'add', // 编辑与新样的标识,
            deptTreeProps: {
                value: 'treeId',
                label: 'name',
                children: 'children'
            },
            selectRoleList: [],
            userId: '',
            node: null
        }
    },
    mounted() {
        this.findPageList()
        // this.getAllRoleList()
        this.getDept()
    },
    activated() {
        console.log('activated')
        this.findPageList()
        // this.getAllRoleList()
        this.getDept()
    },
    deactivated() {
        console.log('deactivated')
    },
    methods: {
        handleNodeClick(node) {
            this.node = node
            if (!node.deptHierarchy) {
                // 判断是公司还是部门
                this.filters.companyId = node.id
                this.filters.deptId = null
            } else {
                this.filters.deptId = node.id
                this.filters.companyId = node.companyId
            }
            this.filters.pageNum = 1
            this.findPageList()
        },

        // 编辑和新增时通过公司id获取部门列表
        getDept() {
            getDeptTableList({
                isValid: 1
            }).then(res => {
                this.deptDataList = res.data
            })
        },
        getFormDept(companyId) {
            getDeptTableList({
                isValid: 1,
                companyId: companyId
            }).then(res => {
                this.formDeptList = res.data
            })
        },
        // 获取分页数据
        findPageList() {
            this.loading = true
            getUserList(this.filters)
                .then(res => {
                    this.tableList = res.data.items
                    this.total = res.data.total
                })
                .finally(() => {
                    this.loading = false
                })
        },
        deptSelect(value) {
            if (value.indexOf('_') === -1) {
                this.dataForm.deptPath = ''
            }
        },
        //授权角色
        handleRole(params) {
            this.userId = params.id
            getAllRoleList({ userId: params.id })
                .then(res => {
                    this.roleList = res.data
                })
                .then(() => {
                    getRoletByUser({ userId: params.id }).then(res => {
                        this.selectRoleList = res.data
                    })
                })

            this.roleDialog = true
        },

        //启用禁用
        handleEnable(row) {
            const tip = row.isLocked === 0 ? '确认启用选中记录吗？' : '确认禁用选中记录吗？'
            confirm(tip)
                .then(() => {
                    userEnable({ userId: row.id, isLocked: row.isLocked })
                        .then(res => {
                            this.$message.success(res.msg)
                            this.findPageList()
                        })
                        .catch(() => {
                            row.isLocked = row.isLocked === 0 ? 1 : 0
                        })
                })
                .catch(() => {
                    row.isLocked = row.isLocked === 0 ? 1 : 0
                })
        },
        // 显示新增界面
        handleAdd() {
            if (this.node && this.node.deptHierarchy) {
                this.getFormDept()
                //如果选择的是部门节点
                this.dialogVisible = true
                this.dataForm = Object.assign({}, this.dataFormDefault)
                this.dataForm.deptPath = this.node.treeId
                this.dialogTag = 'add'
            } else {
                // 如果选择的是公司节点
                this.$message.warning('请选择部门添加用户！')
            }
        },
        // 显示编辑界面
        handleEdit(tag, row) {
            this.getFormDept(row.companyId)
            this.dataForm = Object.assign({}, row)
            this.dialogTag = tag
            this.dialogVisible = true
        },
        // 编辑
        submitForm(data) {
            let fetchApi = this.dialogTag === 'add' ? addUser : editUser
            data.mobile = data.mobile ? data.mobile : null
            fetchApi(data).then(res => {
                this.$message.success(res.msg)
                this.findPageList()
                this.dialogVisible = false
            })
        },
        submitRole(data) {
            userbindRole({
                roleIdList: data,
                userId: this.userId
            }).then(res => {
                this.$message.success(res.msg)
                this.roleDialog = false
                this.findPageList()
            })
        }
    }
}
</script>

<style lang="scss">
.main-content {
    width: 100%;
    height: 100%;
    display: flex;
    // background: #f1f1f1;
    .left-tree {
        margin: 12px 0 12px 12px;
        min-height: 800px;
        height: 80vh;
        flex: 0 0 250px;
        background: #fff;
        padding: 12px;
        box-sizing: border-box;
        .el-card__header {
            font-size: 14px;
            padding: 0;
            line-height: 40px;
        }
        .el-card__body {
            padding: 12px 0;
            .el-tree-node__label {
                font-size: 12px;
            }
        }
    }
    .page-container {
        width: 100%;
        height: 100%;
        flex: auto;
    }
}
</style>
